#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include <string.h>
#include<pthread.h>
#include<iostream>
#include<vector>

using namespace std;
#define LOCAL_IP "192.168.0.105"
#define LOCAL_PORT 8087
#define MAX 10

pthread_mutex_t mutex;
string lastmessage;
struct user{
	int sock;
	string name;
};
vector<int> socks;

int start_up(const char* local_ip,int local_port)
{
	int sock = socket(AF_INET,SOCK_STREAM,0);//1.build socket
	if(sock < 0){
		perror("socket");
		exit(1);
	}
	struct sockaddr_in local;//2.bind the socket to IP and PORT
	local.sin_family = AF_INET;
	local.sin_port = htons(local_port);
	local.sin_addr.s_addr = inet_addr(local_ip);
	const int on=1;

	setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));//set bind options to avoid error
	if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0)//3.bind socket
	{
		perror("bind");
		exit(2);
	}
	else{cout<<"Bind success."<<endl;}
	if(listen(sock,MAX) < 0)
	{
		perror("listen");
		exit(3);
	}
	else{cout<<"Listenning."<<endl;}
	return sock;
}

void * HandlerRequest(void *arg)
{
	pthread_mutex_lock(&mutex);//lock
	user* t = (user*)arg;
	int new_sock = t->sock;
	string idname = t->name;
	char recvBuf[4024] = {0};
	int rRes;
	while(true){
		memset(recvBuf,0,sizeof(char)*4024);
		rRes = recv(new_sock, recvBuf, 4024, 0);
		if(rRes>0)
			cout << "( socketID: " << new_sock << " ) "<< idname << ":" << recvBuf <<endl;
		else{
			cout<<idname<<" is out."<<endl;
			break;
		}

		for(auto i:socks){
			if(i!=new_sock){
				send(i,(char*)recvBuf,strlen(recvBuf),0);
			}
		}
	}
	close(new_sock);
	pthread_mutex_unlock(&mutex);//unlock
	pthread_exit(NULL);
}

int main()
{
	int sock = start_up(LOCAL_IP,LOCAL_PORT);
	char recvBuf[4024] = {0};
	struct sockaddr_in client;
	socklen_t len = sizeof(client);
	while(true){
		pthread_mutex_init(&mutex, NULL);
		memset(recvBuf,0,sizeof(char)*4024);
		int new_sock = accept(sock,(struct sockaddr *)&client,&len);
		if(new_sock>0){
			recv(new_sock, recvBuf, 4024, 0);
			if (recvBuf[0] == '+' || recvBuf[0] == '=' || recvBuf[0] == '!') {
				cout << "( socketID: " << new_sock << " ) web:" << recvBuf << endl;
				for (auto i : socks) {
					if (i != new_sock) {
						send(i, (char*)recvBuf, strlen(recvBuf), 0);
					}
				}
				continue;
			}
			else {
				cout<<endl<<recvBuf<<" is connected."<<"( socket: "<<new_sock<<" )"<<endl;
				cout<<"----------------------"<<endl;
				socks.push_back(new_sock);
				cout<<socks.size()<<" clients connected."<<endl;
			}
		}
		else{
			cout<<"Failed to accept."<<endl;
		}
		user t;
		t.name = recvBuf;
		t.sock = new_sock;
		pthread_t id;
		pthread_create(&id,NULL,HandlerRequest,&t);
		pthread_mutex_destroy(&mutex);
	}
	close(sock);
	return 0;
}



